package web

import (
	"gitee.com/chicken-c/go-learn/webook/internal/service"
	"gitee.com/chicken-c/go-learn/webook/internal/service/oauth2/wechat"
	ijwt "gitee.com/chicken-c/go-learn/webook/internal/web/jwt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type OAuto2WechatHandler struct {
	srv  wechat.OAuthService
	uSrv service.UserService
	ijwt.Handler
}

func NewOAuto2WechatHandler(srv wechat.OAuthService, uSrv service.UserService, jwtHdl ijwt.Handler) *OAuto2WechatHandler {
	return &OAuto2WechatHandler{
		srv:     srv,
		uSrv:    uSrv,
		Handler: jwtHdl,
	}
}

func (w *OAuto2WechatHandler) RegisterRoutes(server *gin.Engine) {
	server.GET("/oauth2/wechat/authurl", w.OAuth2URL)
	server.Any("/oauth2/wechat/callback", w.Callback)
}

func (w *OAuto2WechatHandler) OAuth2URL(ctx *gin.Context) {
	url, err := w.srv.AuthURL(ctx)
	if err != nil {
		ctx.String(http.StatusOK, "系统错误")
		return
	}

	ctx.String(http.StatusOK, url)
}

func (w *OAuto2WechatHandler) Callback(ctx *gin.Context) {
	code := ctx.Query("code")
	state := ctx.Query("state")

	info, err := w.srv.VerilyCode(ctx, code, state)
	if err != nil {
		ctx.String(http.StatusOK, "系统错误")
		return
	}

	//代表微信登录成功
	u, err := w.uSrv.FindOrCreateByWechat(ctx, info)
	if err != nil {
		ctx.String(http.StatusOK, "系统错误")
		return
	}

	//设置JWT
	err = w.SetLoginToken(ctx, u.Id)
	if err != nil {
		ctx.String(http.StatusOK, "系统错误")
		return
	}
	ctx.String(http.StatusOK, "登录成功")
}
